from datetime import datetime
from typing import List, Optional, Dict, Any
from pydantic import BaseModel
from app.models.ai_workflow import TaskStatus, StepStatus


class WorkflowStepBase(BaseModel):
    step_name: str
    step_order: int
    api_provider: Optional[str] = None
    input_data: Optional[Dict[str, Any]] = None


class WorkflowStepCreate(WorkflowStepBase):
    pass


class WorkflowStepResponse(WorkflowStepBase):
    id: int
    workflow_id: int
    status: StepStatus
    external_task_id: Optional[str] = None
    external_conversation_id: Optional[str] = None
    output_data: Optional[Dict[str, Any]] = None
    error_message: Optional[str] = None
    retry_count: int
    created_at: datetime
    updated_at: datetime
    started_at: Optional[datetime] = None
    completed_at: Optional[datetime] = None
    
    class Config:
        from_attributes = True
        json_encoders = {
            datetime: lambda v: v.strftime("%Y-%m-%d %H:%M:%S") if v else None
        }


class AIWorkflowBase(BaseModel):
    task_name: str
    input_data: Optional[Dict[str, Any]] = None
    task_config: Optional[Dict[str, Any]] = None
    execution_summary: Optional[Dict[str, Any]] = None
    expected_outputs: Optional[Dict[str, Any]] = None


class AIWorkflowCreate(AIWorkflowBase):
    steps: Optional[List[WorkflowStepCreate]] = None


class AIWorkflowResponse(AIWorkflowBase):
    id: int
    user_id: int
    status: TaskStatus
    current_step: Optional[str] = None
    progress: int = 0
    result_data: Optional[Dict[str, Any]] = None
    error_message: Optional[str] = None
    retry_count: int = 0
    created_at: datetime
    updated_at: datetime
    started_at: Optional[datetime] = None
    completed_at: Optional[datetime] = None
    steps: Optional[List[WorkflowStepResponse]] = None
    
    class Config:
        from_attributes = True
        json_encoders = {
            datetime: lambda v: v.strftime("%Y-%m-%d %H:%M:%S") if v else None
        }


class WorkflowListResponse(BaseModel):
    id: int
    task_name: str
    status: TaskStatus
    progress: int
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True


class WorkflowCompletionStatus(BaseModel):
    is_complete: bool
    completion_rate: float
    completion_details: Dict[str, Any]
    missing_outputs: List[Dict[str, Any]]
    total_expected: int
    total_actual: int


class ErrorHistoryResponse(BaseModel):
    id: int
    user_id: int
    workflow_id: Optional[int] = None
    step_id: Optional[int] = None
    error_type: Optional[str] = None
    error_message: str
    api_provider: Optional[str] = None
    user_name: Optional[str] = None
    created_at: datetime
    
    class Config:
        from_attributes = True
        json_encoders = {
            datetime: lambda v: v.strftime("%Y-%m-%d %H:%M:%S") if v else None
        }


class UserTaskStatsResponse(BaseModel):
    status_breakdown: Dict[str, int]
    completion_stats: Dict[str, int]
    total_tasks: int


class TaskSummaryResponse(BaseModel):
    total_tasks: int
    pending_tasks: int
    running_tasks: int
    completed_tasks: int
    failed_tasks: int
    success_rate: float


class BatchImageProcessRequest(BaseModel):
    """批量图片处理请求"""
    image_path: List[str]  # 图片URL数组
    prompt: str = ""
    variation_count: int
    batch_name: Optional[str] = None
    
    class Config:
        json_schema_extra = {
            "example": {
                "image_path": [
                    "https://web-site-1304251202.cos.ap-guangzhou.myqcloud.com/image_tasks/e9b00533363446f8b52e48fb26d19323_1755850599.png",
                    "https://web-site-1304251202.cos.ap-guangzhou.myqcloud.com/image_tasks/e9b00533363446f8b52e48fb26d19323_1755850599.png"
                ],
                "prompt": "优化图片",
                "variation_count": 3,
                "batch_name": "测试批次"
            }
        }

class BatchImageProcessResponse(BaseModel):
    """图片处理响应"""
    code: int
    msg: str
    data: Dict[str, Any]  # 包含 workflow_ids (数组), total_images, status
    
class WorkflowBatchInfo(BaseModel):
    """工作流批次信息"""
    workflow_id: int
    batch_index: int
    image_url: str
    original_url: str
    status: str

class BatchCompletionDetailsRequest(BaseModel):
    """批量完成详情查询请求"""
    workflow_ids: List[int]

class WorkflowCompletionDetails(BaseModel):
    """单个工作流完成详情"""
    workflow_id: int
    task_name: str
    status: str
    completion_details: Dict[str, str]  # 格式: {"output_type": "actual/expected"}
    summary: Dict[str, Any]  # 包含 completed, total, completion_rate, is_complete
    error: Optional[str] = None

class BatchCompletionDetailsResponse(BaseModel):
    """批量完成详情查询响应"""
    code: int
    msg: str
    data: Dict[str, Any]  # 包含 workflows, total_count, success_count, query_summary